package com.ls.fw.data.config;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;

import com.ls.fw.data.config.DataConfig;
import com.ls.fw.data.config.DataConfigAdapter;


/**
 * 配置文件信息（系统属性dataconfigpath表示文件路径）默认是/data_config.properties；
 * @author ls
 * 2014年12月6日下午1:46:22
 */
public class DataConfigImpl extends DataConfigAdapter{

	private static DataConfig config = null;
	/**
	 * 默认配置文件路径
	 */
	public static final String DEFAULT_METAINF_path = "/META-INF/data/data_config.properties";
	
	/**
	 * 自定义配置路径
	 */
	public static final String DEFAULT_path = "/data_config.properties";
	
	private Properties properties = new Properties();
	
	private DataConfigImpl(){
		this.init();
		this.putFile(DEFAULT_METAINF_path);
		String path = System.getProperty("dataconfigpath", DEFAULT_path);
		this.putFile(path);
	}
	
	
	
	private void init(){
		properties.put(PARAM_PRIKEYNAME, DEFAULT_ID);
	}
	
	@SuppressWarnings("resource")
	private InputStream getFileInputStream(String path){
		InputStream input = null;
		File file = new File(path);
		if(file.exists()){
			try {
				input =  new FileInputStream(file);
			} catch (FileNotFoundException e) {
				System.err.println("文件【"+path+"】未找到！试图到jar包中加载改文件！");
			}
		}else{
			URL url = DataConfigImpl.class.getResource(path);
			String m_path = "";
			if(url!=null){
				m_path = url.getPath().replaceAll("%20", " ");
			}
			try {
				input =  new FileInputStream(m_path);
			} catch (FileNotFoundException e) {
				System.err.println("文件【"+m_path+"】未找到！试图到jar包中加载改文件！");
				input =  DataConfigImpl.class.getResourceAsStream(path);
				if(input==null){
					System.err.println("jar包中未找到配置文件【"+path+"】");
				}
			}
		}
		if(input!=null){
			System.out.println("配置文件【"+path+"】加载成功！");
		}
		return input;
	}
	
	public static synchronized DataConfig getInstance(){
		if(config==null){
			config = new DataConfigImpl();
		}
		return config;
	}
	
	@Override
	public Properties getProperties() {
		return properties;
	}

	
	public static void main(String[] args) {
		System.out.println(DataConfigImpl.getInstance().getProperties());
	}


	@Override
	public void putFile(String path) {
		InputStream input = null;
		try {
			input = this.getFileInputStream(path);
			if(input != null){
				properties.load(input);
				System.out.println("加载配置文件【"+path+"】后的参数信息："+properties);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			if(input != null){
				try {
					input.close();
				} catch (IOException e) {
				}
			}
		}
	}



	@Override
	public String toString() {
		return "DataConfigImpl [properties=" + properties + "]";
	}
}
